<template>
	<div class="container">
		<div class="table">
			<!-- <div class="crumbs">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item
            ><i class="el-icon-lx-calendar"></i> 账号管理</el-breadcrumb-item
          >
        </el-breadcrumb>
      </div> -->
			<div class="contain">
				<div class="handle-box">
					<el-button type="primary" class="mr20" icon="el-icon-plus" @click="handleNew" v-permission>新建
					</el-button>
					<el-input placeholder="用户帐号" class="handle-input mr10" clearable v-model="searchStrAccount">
						<i class="el-icon-search el-input__icon" slot="prefix"> </i>
					</el-input>
					<!-- <el-input
						placeholder="密码"
						class="handle-input mr10"
						clearable
						v-model="searchStrUser"
					>
						<i class="el-icon-search el-input__icon" slot="prefix">
						</i>
					</el-input> -->
					<!-- <el-date-picker
                    v-model="pickerTime"
                    type="datetimerange"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :picker-options="pickerOptions"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
                </el-date-picker> -->
				</div>
				<!-- :data="
						tableDataFn.slice(
							(cur_page - 1) * pageSize,
							cur_page * pageSize
						)
					" -->
				<el-table v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
					element-loading-background="rgba(0, 0, 0, 0.8)" :data="tableDataFn" border stripe :fit="true"
					class="table" ref="multipleTable" @selection-change="handleSelectionChange">
					<el-table-column type="index" width="50" label="序号">
					</el-table-column>
					<el-table-column prop="USERNAME" align="center" sortable label="用户帐号"></el-table-column>
					<el-table-column prop="NAME" align="center" label="密码">
						<template v-slot="scope">
							<div>
								{{ scope.row["showPswd"] ? scope.row.NAME : "******" }}
								<i class="el-icon-view pswdBtn" style="cursor:pointer"
									@click="showPswdFn(scope.$index, scope.row)"></i>
							</div>
						</template>
					</el-table-column>
					<el-table-column prop="STATUS" align="center" label="状态">
						<template v-slot="scope">
							<!-- <i class="el-icon-s-custom" v-show="scope.row.ADMINISTRATOR == 1"></i>
                        <i class="el-icon-user" v-show="scope.row.ADMINISTRATOR != 1"></i> -->
							<!-- v-if="scope.row.USERNAME!='admin'" -->
							<div v-if="scope.row.ADMINISTRATOR != '0'">
								<template v-if="scope.row.STATUS == 1">
									<el-tag type="success" style="cursor:pointer" @click="frozenAccount(scope.row)">启用
									</el-tag>
								</template>

								<template v-if="scope.row.STATUS == 0">
									<el-tag type="danger" style="cursor:pointer" @click="frozenAccount(scope.row)">禁用
									</el-tag>
								</template>
							</div>
						</template>
					</el-table-column>

					<el-table-column prop="QX" align="center" label="用户类型">
						<template v-slot="scope">
							<!-- <i
                                class="el-icon-s-custom"
                                v-show="scope.row.ADMINISTRATOR == 2"
                            ></i> -->
							<!-- <i
                                class="el-icon-s-custom"
                                v-show="scope.row.ADMINISTRATOR == 0"
                            ></i> -->
							<!-- <i
                                class="el-icon-user"
                                v-show="scope.row.ADMINISTRATOR == 1"
                            ></i> -->
							<!-- <span style="margin-left: 10px" v-show="scope.row.ADMINISTRATOR == 0">
                                {{ scope.row.QX }}
                            </span> -->
							<!-- <span style="margin-left: 10px" v-show="scope.row.ADMINISTRATOR != 0">
                                <div v-for="item in scope.row.ADMINISTRATOR" :key='item'>

								</div>
                            </span> -->
							<template v-for="(item, index) in scope.row.ADMINISTRATOR">
								<div :key="index" style="display: inline">
									<div v-show="item == 0">
										<i class="el-icon-s-custom"></i>
										{{ scope.row.QX }}
									</div>

									<el-tag style="margin:5px" v-show="item == 1" type="info" effect="dark">Database
									</el-tag>

									<el-tag style="margin:5px" v-show="item == 2" type="danger" effect="dark">Server
									</el-tag>

									<el-tag style="margin:5px" v-show="item == 3" type="warning" effect="dark">Network
									</el-tag>
								</div>
							</template>
						</template>
					</el-table-column>
					<el-table-column label="用户权限" align="center">
						<template v-slot="scope">
							<div>
								<div v-show="scope.row.AUTHORITY == 0">
									<i class="el-icon-s-custom"></i>
									管理员
								</div>
								<!-- {{scope.row.AUTHORITY==0?'管理员':'普通用户'}} -->
								<div v-show="scope.row.AUTHORITY == 1">
									<i class="el-icon-user"></i>
									普通用户
								</div>
							</div>
						</template>
					</el-table-column>
					<el-table-column prop="ENDTIME" align="center" label="账户到期时间">
						<template v-slot="scope">
							{{ scope.row.ENDTIME }}
						</template>
					</el-table-column>
					<el-table-column prop="CREATE_DATE" align="center" label="创建日期"></el-table-column>
					<el-table-column label="操作" align="center">
						<template v-slot="scope">
							<!-- v-if="scope.row.USERNAME!='admin'" -->
							<div v-if="scope.row.ADMINISTRATOR != '0'">
								<el-button size="mini" icon="el-icon-document"
									@click="handleEdit(scope.$index, scope.row)" v-permission>编辑
								</el-button>
								<el-button size="mini" type="danger" icon="el-icon-delete" v-permission
									@click="handleDelete(scope.$index, scope.row)">删除
								</el-button>
							</div>
						</template>
					</el-table-column>
				</el-table>
				<!-- <div class="pagination">
					<el-pagination
						background
						:current-page="cur_page"
						@current-change="handleCurrentChange"
						:page-size="pageSize"
						layout="prev, pager, next"
						:total="dataTotal"
					>
					</el-pagination>
				</div>  -->
			</div>

			<!-- 新建、编辑对话框 -->
			<el-dialog :title="dialogTitle" :visible.sync="editVisible" width="60%" :destroy-on-close="true"
				@close="clearData('userForm')" :close-on-click-modal="false">
				<el-form :model="userForm" :rules="rules" ref="userForm" label-width="140px">
					<el-form-item label="用户帐号" prop="username">
						<el-input v-model="userForm.username"></el-input>
					</el-form-item>
					<el-form-item label="密码" v-if="false">
						<el-input v-model="userForm.name"></el-input>
					</el-form-item>
					<el-form-item label="用户类型" v-show="isShowAuth">
						<el-radio-group v-model="userForm.authority">
							<el-radio-button key="1" label="1">普通用户</el-radio-button>
							<el-radio-button key="0" label="0">管理员</el-radio-button>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="权限" v-show="userType == 'superAdmin'" prop="admin">
						<!-- v-show="userType == 'superAdmin'" -->
						<el-checkbox-group v-model="userForm.admin">
							<el-checkbox label="1">DataBase</el-checkbox>
							<el-checkbox label="2">Server</el-checkbox>
							<el-checkbox label="3">Network</el-checkbox>
						</el-checkbox-group>
					</el-form-item>
					<el-form-item label="账户到期时间" prop="endTime" v-show="userType == 'superAdmin'">
						<!-- v-show="userType == 'superAdmin'" -->
						<!-- <el-radio-group @change='changes'
						v-model="userForm.status"
						:fill="userForm.status == 1 ? '#67C23A' : '#F56C6C'"
					>
						<el-radio-button :key="0" label="0"
							>禁用</el-radio-button
						>
						<el-radio-button :key="1" label="1"
							>启用</el-radio-button
						>
					</el-radio-group> -->
						<!-- <el-radio-group
							v-model="STATUS"
							@change="changes"
							:fill="STATUS == 'y' ? '#67C23A' : '#F56C6C'"
						>
							<el-radio-button key="y" label="y"
								>启用</el-radio-button
							>
							<el-radio-button key="n" label="n"
								>禁用</el-radio-button
							>
						</el-radio-group> -->
						<!-- :picker-options="pickerOptions" -->
						<el-date-picker v-model="userForm.endTime" type="datetime" placeholder="选择日期时间">
						</el-date-picker>
					</el-form-item>
					<el-form-item label="密码" prop="password">
						<el-input type="password" v-model="userForm.password" autocomplete="new-password">
						</el-input>
					</el-form-item>
					<el-form-item label="确认密码" prop="password2">
						<el-input type="password" v-model="userForm.password2" autocomplete="new-password">
						</el-input>
					</el-form-item>
				</el-form>

				<span slot="footer">
					<el-button @click="editVisible = false">取 消</el-button>
					<el-button type="primary" @click="submitBtn('userForm')" :disabled="submitBtnDisabled">
						确 定
					</el-button>
				</span>
			</el-dialog>

			<!-- 删除提示框 -->
			<el-dialog title="提示" :visible.sync="delVisible" width="300px" center :destroy-on-close="true"
				:close-on-click-modal="false">
				<div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>
				<span slot="footer" class="dialog-footer">
					<el-button @click="delVisible = false">取 消</el-button>
					<el-button type="primary" @click="deleteRow">确 定</el-button>
				</span>
			</el-dialog>
		</div>
		<v-pagination :dataTotal="postData.dataTotal" :curPage="postData.curPage" :pageSize="postData.pageSize"
			@getCurPage="getPaginationCurPage" @getPageSize="getPaginationPageSize">
		</v-pagination>
	</div>
</template>

<script>
	import {
		fetchData,
		getinfo,
		addUser,
		editUser,
		deleceUser,
	} from "@/api/index";
	import {
		submitLogin
	} from "../../../api/index";
	import bus from "../../common/bus";
	const crypto = require("crypto");
	import moment from "moment";
	import {
		getUserData,
		indexedDb,
		getData,
		DeleteDataBase,
	} from "@/utils/IndexedDB.js";
	import vPagination from "common/Pagination.vue";

	export default {
		components: {
			vPagination
		},
		data() {
			var validatePass = (rule, value, callback) => {
				if (value === "" && this.dialogTitle == "新建") {
					callback(new Error("请输入密码"));
				} else {
					if (this.userForm.password2 !== "") {
						this.$refs.userForm.validateField("password2");
					}
					callback();
				}
			};
			var validatePass2 = (rule, value, callback) => {
				if (value === "" && this.dialogTitle == "新建") {
					callback(new Error("请再次输入密码"));
				} else if (value !== this.userForm.password) {
					callback(new Error("两次输入密码不一致!"));
				} else {
					callback();
				}
			};
			return {
				tableData: [],
				// tableData: '',
				loading: false,
				cur_page: 1,
				dataTotal: 0,
				multipleSelection: [],
				userForm: {
					username: "",
					icd: "",
					name: "",
					admin: [],
					endTime: "",
					status: 1,
					password: "",
					password2: "",
					creattime: "",
					authority: 0,
				},
				rules: {
					password: [{
							required: true,
							message: "请输入密码"
						},
						// {
						// 	pattern: /^(?=.*[a-z])(?=.*[0-9])(?=.*[._~!@#$^&*])[a-z0-9._~!@#$^&*]{6,18}$/,
						// 	message: "密码必须由小写字母、数字、特殊符号组成,特殊符号包含（. _ ~ ! @ # $ ^ & *),长度为6-18位",
						// },
						{
							validator: validatePass,
							trigger: "blur"
						},
					],
					password2: [{
							required: true,
							message: "请再次输入密码"
						},
						// {
						// 	pattern: /^(?=.*[a-z])(?=.*[0-9])(?=.*[._~!@#$^&*])[a-z0-9._~!@#$^&*]{6,18}$/,
						// 	message: "密码必须由小写字母、数字、特殊符号组成,特殊符号包含（. _ ~ ! @ # $ ^ & *),长度为6-18位",
						// },
						{
							validator: validatePass2,
							trigger: "blur"
						},
					],
					admin: [{
						required: true,
						message: "请选择权限类型"
					}],
					username: [{
						required: true,
						message: "请输入账号"
					}],
					endTime: [{
						required: true,
						message: "请输入账户到期时间"
					}],
				},
				idx: -1,
				id: -1,
				sn: -1,
				deleteName: "",
				dialogTitle: "",
				operaVal: "",
				editVisible: false,
				delVisible: false,
				pageSize: 10,
				searchStrAccount: "",
				searchStrUser: "",
				pickerOptions: {
					shortcuts: [{
							text: "最近一周",
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
								picker.$emit("pick", [start, end]);
							},
						},
						{
							text: "最近一个月",
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
								picker.$emit("pick", [start, end]);
							},
						},
						{
							text: "最近三个月",
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
								picker.$emit("pick", [start, end]);
							},
						},
					],
				},
				pickerTime: [],
				submitBtnDisabled: false,
				systemEndTime: {
					// Forbid: new Date(),
					Forbid: moment(new Date()).format("YYYY/MM/DD HH:mm:ss"),
					permanent: "3000/05/01 11:00:00",
				},
				checkList: [],
				userType: "",
				power: "",
				userEndTime: "",
				isShowAuth: true,
				ROLETYPE: "",
				ICD: "",

				postData: {
					opera: "",
					// 当前页数
					curPage: 1,
					//每页显示个数
					pageSize: 10,
					//总条目数
					dataTotal: 0,
					tableDataTotal: []
					// sort: {
					// 	sortColumn: '',
					// 	sortOrders: '',
					// },
					// filtersType: 'exactquery', // 精确查询
					// filters: {},
				},
				// pickerOptions: {
				// 	disabledDate(time) {
				// 		return time.getTime() < Date.now()-8.64e6; //如果没有后面的-8.64e6就是不可以选择今天的
				// 	},
				// },
			};
		},
		created() {
			// this.deleteDb()
			// this.getData();
			// this.deleteDb()

			if (this.searchStrAccount == '') {
				this.getData()
			}
			bus.$on("refData_users", (msg) => {
				this.getData();
			});
		},
		computed: {
			tableDataFn() {
				this.dataTotal = 0;
				this.cur_page = 1;

				return this.tableData.filter((d) => {
					let _username = d.USERNAME;
					let _name = d.NAME;
					d["showPswd"] = false;
					// if (
					//   _username.includes(this.searchStrAccount) &&
					//   _name.includes(this.searchStrUser)
					// ) {
					if (d.ADMINISTRATOR == 0) {
						d.QX = "超级管理员";
					} else if (d.ADMINISTRATOR == 1) {
						d.QX = "普通用户";
					} else {
						d.QX = "管理员";
					}

					if (this.pickerTime != null && this.pickerTime.length > 0) {
						let _time = new Date(d.CREATE_DATE).getTime();
						let _startTime = new Date(this.pickerTime[0]).getTime();
						let _endTime = new Date(this.pickerTime[1]).getTime();
						if (_time >= _startTime && _time <= _endTime) {
							this.dataTotal += 1;
							return d;
						}
					} else {
						this.dataTotal += 1;
						return d;
					}
					// }
				});
			},
			STATUS: {
				get: function() {
					return this.userForm.status === 1 ? "y" : "n";
				},
				set: function(value) {
					this.userForm.status = value === "y" ? 1 : 0;
				},
			},
		},
		methods: {
			// 分页导航
			handleCurrentChange(val) {
				this.cur_page = val;
			},
			// 获取 数据
			async getData() {
				// fetchData({
				// 	OPERA: 'userlist',
				// }).then((res) => {
				// 	console.log(res)
				// });
				await getUserData("userBase", "infoBase", 0).then((res) => {
					this.userType = res.ms_type;
					this.power = res.power;
					// this.userAuthority = res.userAuthority;
					this.userEndTime = res.endTime;
					this.ROLETYPE = res.roleType;
					this.ICD = res.icd;
				});
				await getinfo({
						power: this.power
					})
					.then((res) => {
						this.loading = true;
						this.tableData = [];
						let tablelistData = [];
						// let item = new Set();
						// let itemkey = [];
						// for (; item.size < res.length; ) {
						//   item.add(
						//     "key" + Math.floor(Math.random() * 1000 * 1000 * 1000) + 1
						//   );

						//   if (item.size == res.length) {
						//     itemkey.push(...item);
						//   }
						// }

						let promiseData = new Promise((resolve, reject) => {
							// this.deleteDb()

							for (let index = 0; index < res.length; index++) {
								let data = {
									USERNAME: res[index].un,
									NAME: res[index].up,
									ADMINISTRATOR: this.NumberToArr(res[index].pw),
									CREATE_DATE: res[index].ct,
									ENDTIME: res[index].et,
									icd: res[index].icd,
									UID: res[index].icd + res[index].up + res[index].un,
									AUTHORITY: res[index].rk,
									PASSWORD: res[index].up,
									STATUS: new Date(res[index].et).getTime() - new Date().getTime() <
										0 ?
										0 :
										1,
								};

								tablelistData.push(data);
							}
							resolve(tablelistData);

						});

						promiseData.then((res) => {

							this.postData.dataTotal = res.length;
							this.tableDataTotal = res
							// console.log(res)
							this.getUserlist(res)
							tablelistData = []
						});






						this.loading = false;
					})
					.catch((err) => {});


			},
			async getUserlist(data) {
				// console.log(data)

				await indexedDb("UserListBase", data, "infoBase", "UID");
				this.tableData = await getData("UserListBase", "infoBase", this.postData);
				// (res)


			},
			// 保存表格勾选数据
			handleSelectionChange(val) {
				this.multipleSelection = val;
			},
			// 提交按钮
			submitBtn(formName) {
				// 验证
				this.$refs[formName].validate((valid) => {
					if (valid) {
						this.submitForm();
					} else {
						return false;
					}
				});
			},
			// 提交数据
			submitForm() {
				// 禁用按钮
				this.submitBtnDisabled = true;
				// 加密
				const md5 = crypto.createHash("md5");
				md5.update(this.userForm.password);

				// 处理权限
				let userType = "";
				this.userForm.admin.sort((a, b) => (a > b ? 1 : a < b ? -1 : 0));
				this.userForm.admin.forEach((item) => {
					if (item == 1) {
						userType += "1";
					} else if (item == 2) {
						userType += "2";
					} else if (item == 3) {
						userType += "3";
					}
				});

				console.log(this.userType)
				let _Adddata = {
					endtime: this.userType == "superAdmin" ?
						moment(this.userForm.endTime).format("YYYY/MM/DD HH:mm:ss") :
						moment(this.userEndTime).format("YYYY/MM/DD HH:mm:ss"),

					username: this.userForm.username,
					power: this.userType == "superAdmin" ? userType : this.power,
					password: this.userForm.password,
					rk: this.userForm.authority,
				};
				let _editdata = {
					endtime: this.userType == "superAdmin" ?
						moment(this.userForm.endTime).format("YYYY/MM/DD HH:mm:ss") :
						moment(this.userEndTime).format("YYYY/MM/DD HH:mm:ss"),
					username: this.userForm.username,
					power: this.userType == "superAdmin" ? userType : this.power,
					password: this.userForm.password,
					creattime: this.userForm.creattime,
					id: this.userForm.icd,
					rk: this.userForm.authority,
				};

				switch (this.dialogTitle) {
					case "新建":
						addUser(_Adddata)
							.then((res) => {
								console.log(res);
								if (res == "add success") {
									this.$message.success({
										message: "操作成功",
										duration: 1000,
									});
									this.editVisible = false;
									this.deleteDb()
									this.getData();
								} else {
									this.$message.error({
										message: "操作失败",
										duration: 1000,
									});
									this.editVisible = false;
								}
							})
							.catch((err) => {
								this.$message.error({
									message: "操作失败",
									duration: 1000,
								});
								this.editVisible = false;
							});

						break;
					case "编辑":
						editUser(_editdata)
							.then((res) => {
								// console.log(res);
								// if (res == "update success") {
								//     this.$message.success({
								//         message: "操作成功",
								//         duration: 1000,
								//     });
								//     this.editVisible = false;
								//     this.getData();
								// } else {
								//     this.$message.error({
								//         message: "操作失败",
								//         duration: 1000,
								//     });
								//     this.editVisible = false;
								// }
								this.$message.success({
									message: "操作成功",
									duration: 1000,
								});
								this.editVisible = false;
								this.deleteDb()
								this.getData();
							})
							.catch((err) => {
								this.$message.error({
									message: "操作失败",
									duration: 1000,
								});
								this.editVisible = false;
							});
						break;
				}
				// 数据
				// let _data = {
				// 	opera: this.operaVal,
				// 	username: this.userForm.username,
				// 	name: this.userForm.name,
				// 	password: md5.digest('hex'),
				// 	admin: this.userForm.admin,
				// };

				// let _data = {
				// 	opera: "LOGINADD",
				// 	username: "root",
				// 	name: "王五",
				// 	password:"123456",
				// 	admin: 1,
				// };
				// if (this.dialogTitle == '编辑') {
				// 	_data.id = this.id;
				// }

				// submitLogin(_data).then((res) => {
				// 	if (res == 'True') {
				// 		bus.$emit('refData_users');
				// 		this.$message.success({
				// 			message: '操作成功',
				// 			duration: 1000,
				// 		});
				// 		this.editVisible = false;
				// 	} else {
				// 		//
				// 		if (/^ORA-00001/.test(res)) {
				// 			this.$message.error('帐号已存在！');
				// 		} else {
				// 			this.$message.error('操作失败');
				// 		}
				// 	}
				// 	// 恢复按钮
				// 	this.submitBtnDisabled = false;
				// });
				this.submitBtnDisabled = false;
			},
			// 新建
			handleNew() {
				this.editVisible = true;
				this.dialogTitle = "新建";
				this.operaVal = "LOGINADD";
				this.userForm.endTime = this.userType == 'superAdmin' ? '' : this.userEndTime;
				this.userForm.admin = this.userType == 'superAdmin' ? [] : this.NumberToArr(this.power);
			},
			// 编辑
			handleEdit(index, row) {
				this.editVisible = true;
				this.dialogTitle = "编辑";
				this.operaVal = "LOGINMOD";
				this.id = row.ID;
				this.userForm.icd = row.icd;
				this.userForm.username = row.USERNAME;
				this.userForm.name = row.NAME;
				this.userForm.admin = row.ADMINISTRATOR;
				this.userForm.status = row.STATUS;
				this.userForm.authority = row.AUTHORITY;
				this.userForm.creattime = moment(row.CREATE_DATE).format(
					"YYYY/MM/DD HH:mm:ss"
				);
				this.userForm.endTime = row.ENDTIME;
				this.userForm.password = row.NAME;
				this.userForm.password2 = row.NAME;
				this.isShowAuth = this.ROLETYPE != "superAdmin" ? false : true;
			},
			// 删除弹窗
			handleDelete(index, row) {
				this.idx = index;
				this.id = row.icd;
				this.delVisible = true;
				this.deleteName = row.USERNAME;
			},
			// 提交删除
			deleteRow() {
				// submitLogin({
				// 	OPERA: 'LOGINDEL',
				// 	ID: this.id,
				// }).then((res) => {
				// 	if (res == 'True') {
				// 		this.$message.success({
				// 			message: '操作成功',
				// 			duration: 1000,
				// 		});
				// 		this.delVisible = false;
				// 		if (this.tableData[this.idx].ID === this.id) {
				// 			this.tableData.splice(this.idx, 1);
				// 		} else {
				// 			for (let i = 0; i < this.tableData.length; i++) {
				// 				if (this.tableData[i].ID === this.id) {
				// 					this.tableData.splice(i, 1);
				// 					return;
				// 				}
				// 			}
				// 		}
				// 	} else {
				// 		this.$message.error({
				// 			message: '操作失败',
				// 		});
				// 	}
				// });
				// console.log(row)

				if (this.ICD == this.id) {
					this.$message.error({
						message: "违规操作,请切换账号重试",
						duration: 3000,
					});
					this.delVisible = false;
					return;
				}

				deleceUser({
						username: this.deleteName
					})
					.then((res) => {
						if (res == "dele success") {
							this.$message.success({
								message: "操作成功",
								duration: 1000,
							});
							this.delVisible = false;
							this.deleteDb()
							this.getData();
						} else {
							this.$message.error({
								message: "操作失败",
								duration: 1000,
							});
							this.delVisible = false;
						}
						this.deleteName = "";
					})
					.catch((err) => {
						this.delVisible = false;
						this.$message.error({
							message: "操作失败",
							duration: 1000,
						});
						this.deleteName = "";
					});
			},
			// 自定义排序
			sortBySum(obj1, obj2) {
				let val1 = obj1.SUMVALUE;
				let val2 = obj2.SUMVALUE;
				return val1 - val2;
			},
			// 关闭时清除数据
			clearData(formName) {
				this.userForm = {
					username: "",
					name: "",
					admin: [],
					password: "",
					password2: "",
					status: 1,
					endTime: "",
					icd: "",
					authority: 0,
				};
				this.isShowAuth = true;
				this.$refs[formName].resetFields();
			},
			changes() {
				// console.log(this.userForm.status);
			},
			frozenAccount(row) {
				if (this.userType != "superAdmin") {
					this.$message.error({
						message: "操作失败,您没有权限",
						duration: 1000,
					});
					return;
				}

				switch (row.STATUS) {
					case 1:
						this.$confirm("是否禁用该用户", "确认信息", {
								distinguishCancelAndClose: true,
								confirmButtonText: "确定",
								cancelButtonText: "放弃",
							})
							.then(() => {
								let powerInfo = "";
								for (let i = 0; i < row.ADMINISTRATOR.length; i++) {
									powerInfo += row.ADMINISTRATOR[i];
								}
								console.log(row);
								let _editdata = {
									endtime: moment(this.systemEndTime.Forbid).format(
										"YYYY/MM/DD HH:mm:ss"
									),
									username: row.USERNAME,
									power: powerInfo,
									password: row.PASSWORD,
									creattime: moment(row.CREATE_DATE).format(
										"YYYY/MM/DD HH:mm:ss"
									),
									id: row.icd,
									rk: row.AUTHORITY,
								};
								editUser(_editdata)
									.then((res) => {
										// console.log(res);
										// if (res == "update success") {
										//     this.$message.success({
										//         message: "操作成功",
										//         duration: 1000,
										//     });
										//     this.editVisible = false;
										//     this.getData();
										// } else {
										//     this.$message.error({
										//         message: "操作失败",
										//         duration: 1000,
										//     });
										//     this.editVisible = false;
										// }
										this.$message.success({
											message: "操作成功",
											duration: 1000,
										});
										this.editVisible = false;
										this.deleteDb()
										this.getData();
									})
									.catch((err) => {
										this.$message.error({
											message: "操作失败",
											duration: 1000,
										});
										this.editVisible = false;
									});
								// this.$message({
								// 	type: 'success',
								// 	message: '操作成功',
								// });
							})
							.catch(() => {
								this.$message({
									type: "error",
									message: "已取消操作",
								});
							});
						break;

					case 0:
						this.$confirm("是否启用该用户", "确认信息", {
								distinguishCancelAndClose: true,
								confirmButtonText: "确定",
								cancelButtonText: "放弃",
							})
							.then(() => {
								// this.$set(this.tableData,'STATUS',1)
								// console.log(row)
								let powerInfo = "";
								for (let i = 0; i < row.ADMINISTRATOR.length; i++) {
									powerInfo += row.ADMINISTRATOR[i];
								}

								let _editdata = {
									endtime: moment(this.systemEndTime.permanent).format(
										"YYYY/MM/DD HH:mm:ss"
									),
									username: row.USERNAME,
									power: powerInfo,
									password: row.PASSWORD,
									creattime: moment(row.CREATE_DATE).format(
										"YYYY/MM/DD HH:mm:ss"
									),
									id: row.icd,
									rk: row.AUTHORITY,
								};
								editUser(_editdata)
									.then((res) => {
										// console.log(res);
										// if (res == "update success") {
										//     this.$message.success({
										//         message: "操作成功",
										//         duration: 1000,
										//     });
										//     this.editVisible = false;
										//     this.getData();
										// } else {
										//     this.$message.error({
										//         message: "操作失败??",
										//         duration: 1000,
										//     });
										//     this.getData();
										//     this.editVisible = false;
										// }
										this.$message.success({
											message: "操作成功",
											duration: 1000,
										});
										this.getData();
										this.deleteDb()
										this.editVisible = false;
									})
									.catch((err) => {
										this.$message.error({
											message: "操作失败",
											duration: 1000,
										});
										this.editVisible = false;
									});
							})
							.catch((err) => {
								this.$message({
									type: "error",
									message: "已取消操作",
								});
							});
						break;
				}
			},
			showPswdFn(index, row) {
				row["showPswd"] = !row["showPswd"];

				this.$set(this.tableDataFn, index, row);
			},
			NumberToArr(num) {
				let str = num.toString();
				let arr = str.split("");
				// console.log(arr);

				// return arr.map((item) => Number(item));
				return arr;
			},
			getPaginationCurPage(val) {
				this.postData.curPage = val;

				this.handlepagination();
			},
			getPaginationPageSize(val) {
				// 分页大小改变之后，重置当前页码为 1
				this.postData.curPage = 1;
				this.postData.pageSize = val;

				this.handlepagination();
			},
			handlepagination() {
				this.tableData = getData("UserListBase", "infoBase", this.postData);
			},
			deleteDb() {
				DeleteDataBase("UserListBase", "infoBase");
			},
			SelectTable() {
				this.deleteDb()
				let filterData = this.tableDataTotal.filter((d) => {
					let _username = d.USERNAME

					return _username.includes(this.searchStrAccount)
				})
				this.tableData = []

				this.getUserlist(filterData)
				this.postData.dataTotal = filterData.length;
				filterData = []
				// this.searchStrAccount=''


			}
			//  handleCurrentChange(currentRow, oldCurrentRow) {
			//     // if (currentRow != null) {
			//     //     currentRow['isEdit'] = true;
			//     // }
			//     // if (oldCurrentRow != null) {
			//     //     oldCurrentRow['isEdit'] = false;
			//     // }
			// 	console.log(currentRow,oldCurrentRow)
			// },
		},
		mounted() {
			// this.$nextTick(() => {
			//     this.$refs.inputRef.focus()
			// })
		},
		watch: {
			'searchStrAccount': function(newVal, oldVal) {
				this.SelectTable()


			}

		},
		beforeDestroy() {
			this.deleteDb();
			this.searchStrAccount = ''

		},
		destroyed() {

		},
		beforeUpdate() {


		},
	};
</script>

<style scoped>
	.handle-box {
		margin-bottom: 20px;
	}

	.handle-select {
		width: 120px;
	}

	.handle-input {
		width: 200px;
		display: inline-block;
	}

	.del-dialog-cnt {
		font-size: 16px;
		text-align: center;
	}

	.table {
		width: 100%;
		/* max-width: 1200px; */
		font-size: 14px;
	}

	.red {
		color: #ff0000;
	}

	.mr10 {
		margin-right: 10px;
	}

	.mr20 {
		margin-right: 20px;
	}

	.pswdBtn {
		float: right;
		line-height: 23px;
		color: #67c23a;
		font-size: 18px;
	}
</style>
